Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
JavaScript document.createElement("a") problem with a.href attribute

Is this behaviour normal when creating a link with document.createElement("a") ?

function updateUl(newVal){
    let a = document.createElement("a")
    let newListItem = document.createElement("li")

    a.appendChild(document.createTextNode(newVal))
    console.log(newVal) //output: "www.google.com"
    a.href = newVal
    console.log(a.href) //output: "http://127.0.0.1:5500/www.google.com"
    a.target = "_blank"
    newListItem.appendChild(a)
    ulEl.appendChild(newListItem)
}

Then clearly when I click on the link I get a page not found error.

What's going on?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Without a protocol, it's assumed to be a route on the current page. Add the https:// protocol to make it navigate.

function updateUl(newVal){ // pass in as "https://www.google.com"
    let a = document.createElement("a")
    let newListItem = document.createElement("li")

    a.appendChild(document.createTextNode(newVal))
    console.log(newVal) //output: "https://www.google.com"
    a.href = newVal
    console.log(a.href) //output: "https://www.google.com"
    a.target = "_blank"
    newListItem.appendChild(a)
    ulEl.appendChild(newListItem)
}

or add it dynamically

function updateUl(newVal){
    if (!newVal.startsWith("http://") && !newVal.startsWith("https://") {
        newVal = `https://{newVal}`;
    }
    let a = document.createElement("a")
    let newListItem = document.createElement("li")

    a.appendChild(document.createTextNode(newVal))
    console.log(newVal) //output: "https://www.google.com"
    a.href = newVal
    console.log(a.href) //output: "https://www.google.com"
    a.target = "_blank"
    newListItem.appendChild(a)
    ulEl.appendChild(newListItem)
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda